package com.aicre.wuliuapp.app.activity;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.aicre.wuliuapp.app.R;
import com.aicre.wuliuapp.app.util.Globles;
import com.aicre.wuliuapp.app.util.String2Request;
import com.aicre.wuliuapp.app.view.XListView;
import com.android.volley.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MatchActivity extends BaseActivity implements XListView.IXListViewListener {
    private ArrayList<HashMap<String, String>> list;

    private MyBaseAdapter mMyBaseAdapter;
    private XListView mLIstView;
    private SimpleDateFormat format;
    private ProgressDialog pd;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home);



        ActionBar bar = this.getActionBar();
        bar.setTitle("全部");
        format=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setMessage("加载中...");
        pd.show();
        intent = getIntent();
        final String from  = intent.getStringExtra("from");
        Log.v("match from",from);
        final String to  = intent.getStringExtra("to");

        list = new ArrayList<HashMap<String, String>>();
        mLIstView = (XListView) findViewById(R.id.lei_x_list_view);
        mMyBaseAdapter = new MyBaseAdapter(this.getBaseContext());
        mLIstView.setAdapter(mMyBaseAdapter);
        mLIstView.setXListViewListener(this);
        mLIstView.setPullRefreshEnable(true);
        mLIstView.setPullLoadEnable(false);
        mLIstView.setRefreshTime(""+format.format(new Date(System.currentTimeMillis())));
        mLIstView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position < 1)
                    return;
                HashMap<String,String> map = list.get(position-1) ;
                Intent i = new Intent(MatchActivity.this, DetailActivity.class);
                i.putExtra("id",map);
                startActivity(i);
            }
        });

        executeRequest(new String2Request(Globles.INFOLIST_URL2, "utf-8",responseListener(),
                errorListener()) {
            protected Map<String, String> getParams() {
                //return new ApiParams().with("param1", "02").with("param2", "14");
                Map<String, String> m = new HashMap<String, String>();
                m.put("num", "0");
                m.put("from", from);
                m.put("to", to );
                Log.v("match location",from+"  "+to);
                return m;
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_match, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private Response.Listener<String> responseListener(){
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("jsoninhome", s);
                JsontoArrayList(s);
                Log.i("Lei","refresh succeed!");
                mMyBaseAdapter.notifyDataSetInvalidated();
                mLIstView.stopRefresh();
                pd.dismiss();
            }
        };
    }

    @Override
    public void onRefresh() {
        mLIstView.setRefreshTime(""+format.format(new Date(System.currentTimeMillis())));
        final String from  = intent.getStringExtra("from");
        final String to  = intent.getStringExtra("to");
        executeRequest(new String2Request(Globles.INFOLIST_URL2, "utf-8",responseListener(),
                errorListener()) {
            protected Map<String, String> getParams() {
                //return new ApiParams().with("param1", "02").with("param2", "14");
                Map<String, String> m = new HashMap<String, String>();
                m.put("num", "0");
                m.put("from", from);
                m.put("to", to );
                Log.v("match location",from+"  "+to);
                return m;
            }
        });
    }

    @Override
    public void onLoadMore() {
        mLIstView.stopLoadMore();
    }


    public ArrayList<HashMap<String,String>> JsontoArrayList(String Json){
        int num = -1;
        JSONObject obj;
        HashMap<String,String> map;
        list.clear();
        try {
            obj = new JSONObject(Json);
            Log.i("JsonObj",obj.toString());
            num = Integer.parseInt(obj.getString("num"));
            Log.i("JsonInHome",""+num);
            JSONArray objArray = obj.getJSONArray("array");
            for (int i = 0;i<num ; i++){
                obj = objArray.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("id",obj.getString("id"));
                map.put("fp",obj.getString("fp"));
                map.put("fc",obj.getString("fc"));
                map.put("fd",obj.getString("fd"));
                map.put("tp",obj.getString("tp"));
                map.put("tc",obj.getString("tc"));
                map.put("td",obj.getString("td"));
                map.put("gn",obj.getString("gn"));
                map.put("gv",obj.getString("gv"));
                map.put("gw",obj.getString("gw"));
                map.put("ct",obj.getString("ct"));
                map.put("cs",obj.getString("cs"));
                map.put("name",obj.getString("name"));
                map.put("date",obj.getString("date"));
                map.put("phone",obj.getString("phone"));
                map.put("time",obj.getString("time"));
                map.put("price",obj.getString("price"));
                map.put("info",obj.getString("info"));
                list.add(map);
            }
        }catch (JSONException e){
            e.toString();
        }
        return list;
    }

    class MyBaseAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public MyBaseAdapter(Context context){
            this.mInflater = LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_infor1,null);
                holder = new ViewHolder();
                holder.mStart = (TextView)convertView.findViewById(R.id.start);
                holder.mDestination = (TextView)convertView.findViewById(R.id.destination);
                holder.mWeight = (TextView) convertView.findViewById(R.id.weight);
                holder.mLength = (TextView) convertView.findViewById(R.id.length);
                holder.mTiji = (TextView) convertView.findViewById(R.id.tiji);     //车体积
                holder.mTime = (TextView) convertView.findViewById(R.id.time);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            final HashMap<String,String> map = list.get(position) ;

            if((map.get("fp").length()+map.get("fc").length())>6){
                int size=map.get("fp").length()+map.get("fc").length();
                StringBuffer sb=new StringBuffer(map.get("fp")+map.get("fc"));
                sb.delete(5,size);
                sb.insert(5,"...");
                holder.mStart.setText(sb.toString());
            }else{
                holder.mStart.setText(map.get("fp")+map.get("fc"));
            }
            if((map.get("tp").length()+map.get("tc").length())>6){
                int size=map.get("tp").length()+map.get("tc").length();
                StringBuffer sb=new StringBuffer(map.get("tp")+map.get("tc"));
                sb.delete(5,size);
                sb.insert(5,"...");
                holder.mDestination.setText(sb.toString());
            }else{
                holder.mDestination.setText(map.get("tp")+map.get("tc"));
            }
            holder.mTiji.setText(map.get("gv")+"方");

            if(!map.get("gw").equals("")) {

                holder.mWeight.setText(map.get("gw")+"吨" );
            }
            holder.mLength.setText(map.get("cs")+"米");
            if(!map.get("time").equals("")) {

                holder.mTime.setText(map.get("time"));
            }

            return convertView;
        }
    }

    /**存放控件*/
    public final class ViewHolder{
        public TextView mTiji;
        public TextView mStart;
        public TextView mDestination;
        public TextView mKindCargo;
        public TextView mWeight;
        public TextView mKindCar;
        public TextView mLength;
        public TextView mContectMan;
        public TextView mNumber;
        public TextView mTime;
        public Button mBtn;
    }
}
